package com.design.YiTong.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.design.YiTong.article.mapper.articleMapper;
import com.design.YiTong.article.service.articleService;
import com.design.YiTong.model.article.articleInfo;
import org.springframework.stereotype.Service;

import java.io.*;

@Service
public class articleServiceImpl extends
        ServiceImpl<articleMapper, articleInfo> implements articleService {
    @Override
    public IPage<articleInfo> showArticle(Page<articleInfo>pageParam) {
        QueryWrapper<articleInfo>wrapper=new QueryWrapper<>();
        IPage<articleInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        return pages;
    }

    @Override
    public articleInfo getActicle(Long id) {
        articleInfo article=baseMapper.selectById(id);
        String url="";
        String image="";
        if(article.getImage()!=null||!article.getImage().equals("")) {
            try {
                BufferedReader br = new BufferedReader(new FileReader(article.getImage()));
                while (true) {
                    url = br.readLine();//readLine()读入一行后会自动换行
                    if (url==null) break;
                    image+=url;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        article.setImage(image);
        return article;
    }

    @Override
    public void saveOrupdataActicle(articleInfo article) {
        articleInfo Info=getActicle(article.getId());
        File file=new File(Info.getId().toString());
        if(Info==null){
            if(article.getImage()!=null) {
                try {
                    file.createNewFile();
                    FileWriter write = new FileWriter("Art"+Info.getId().toString());
                    BufferedWriter bw = new BufferedWriter(write);
                    bw.write(article.getImage());
                    bw.close();
                    write.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            article.setImage("Art"+Info.getId().toString());
            baseMapper.insert(article);
        }
        if(article.getImage()!=null) {
            try {
                FileWriter write = new FileWriter(Info.getId().toString());
                BufferedWriter bw = new BufferedWriter(write);
                bw.write(article.getImage());
                bw.close();
                write.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        article.setImage("Art"+Info.getId().toString());
        baseMapper.updateById(article);
    }
}
